<template>
  <div class="user-profile">
    <div class="avatar">
      <a href="javascript:;" @click="changeAvatar()">
        <img :src="profile.avatar" alt="" />
      </a>
      <p>点击上传头像</p>
    </div>
    <Form>
      <Field
        label="昵称"
        v-model="profile.nickname"
        placeholder="请输入昵称"
      ></Field>
      <Field label="性别">
        <template #input>
          <RadioGroup
            icon-size="18"
            checked-color="#27ba9b"
            v-model="profile.gender"
            direction="horizontal"
          >
            <Radio name="男">男</Radio>
            <Radio name="女">女</Radio>
          </RadioGroup>
        </template>
      </Field>
      <Field
        label="出生日期"
        clickable
        readonly
        :value="profile.birthday"
        placeholder="点击选择时间"
        @click="openDatePicker()"
      ></Field>
      <Field
        label="城市"
        clickable
        readonly
        :value="profile.fullLocation"
        placeholder="点击选择城市"
        @click="openAreaPicker()"
      ></Field>
      <Field
        label="职业"
        clickable
        readonly
        :value="profile.profession"
        placeholder="点击选择职业"
        @click="openProfessionPicker()"
      ></Field>
    </Form>
    <Button @click="submit" type="primary" style="width:100%;marginTop:12px">保存</Button>
    <!-- 日期选择 -->
    <Popup v-model="showDatePicker" position="bottom">
      <DatetimePicker
        title="日期选择"
        type="date"
        :max-date="maxDate"
        :min-date="minDate"
        v-model="defaultDate"
        @confirm="onConfirmDate"
        @cancel="showDatePicker = false"
      />
    </Popup>
    <!-- 城市选择 -->
    <Popup v-model="showAreaPicker" position="bottom">
      <Area
        title="城市选择"
        :area-list="areaList"
        @confirm="onConfirmArea"
        @cancel="showAreaPicker = false"
      />
    </Popup>
    <!-- 职业选择 -->
    <Popup v-model="showProfessionPicker" position="bottom">
      <Picker
        title="职业选择"
        show-toolbar
        value-key="label"
        :columns="professionList"
        @confirm="onConfirmProfession"
        @cancel="showProfessionPicker = false"
      />
    </Popup>
  </div>
</template>

<script>
import {
  Form,
  Field,
  RadioGroup,
  Radio,
  Popup,
  DatetimePicker,
  Area,
  Picker,
  Toast,
  Button
} from 'vant'
import dayjs from 'dayjs'
import areaList from '@/api/area'
import professionList from '@/api/profession'
import emitter from '@/hybrid/emitter'
// import { mapMutations } from 'vuex'
import http from '@/api/http'
import avatar from '@/assets/images/user_default.jpg'
export default {
  name: 'UserProfile',
  components: {
    Form,
    Field,
    RadioGroup,
    Radio,
    Popup,
    DatetimePicker,
    Area,
    Picker,
    Button
  },
  data () {
    return {
      profile: {
        nickname: '',
        birthday: '',
        gender: '男',
        countyCode: '',
        cityCode: '',
        provinceCode: '',
        profession: '',
        fullLocation: '',
        avatar
      },
      initAvatar: avatar,
      previewAvatar: null,
      // 日期
      showDatePicker: false,
      maxDate: new Date(),
      minDate: new Date('1960-01-01'),
      defaultDate: new Date(),
      // 城市
      showAreaPicker: false,
      areaList,
      // 职业
      professionList,
      showProfessionPicker: false
    }
  },
  methods: {
    openDatePicker () {
      this.showDatePicker = true
    },
    onConfirmDate (val) {
      this.showDatePicker = false
      this.profile.birthday = dayjs(val).format('YYYY-MM-DD')
    },
    openAreaPicker () {
      this.showAreaPicker = true
    },
    onConfirmArea (val) {
      this.showAreaPicker = false
      this.profile.provinceCode = val[0].code
      this.profile.cityCode = val[1].code
      this.profile.countyCode = val[2].code
      this.profile.fullLocation = val.reduce((a, b) => a + b.name, '')
    },
    openProfessionPicker () {
      this.showProfessionPicker = true
    },
    onConfirmProfession (val) {
      this.showProfessionPicker = false
      this.profile.profession = val.label
    },
    changeAvatar () {
      window.FlutterUserIcon && window.FlutterUserIcon.postMessage('点击头像')
    },
    base64toFile (base64Data) {
      // 去掉base64的头部信息，并转换为byte
      const split = base64Data.split(',')
      const bytes = window.atob(split[1])
      // 获取文件类型
      const fileType = split[0].match(/:(.*?);/)[1]
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      return new Blob([ab], { type: fileType })
    },
    async submit () {
      Toast.loading('正在提交')
      try {
        if (this.profile.avatar !== this.initAvatar) {
          const fd = new FormData()
          fd.append('file', this.base64toFile(this.profile.avatar), 'image.png')
          // 头像
          await http.post('/member/profile/avatar', fd)
        }
        // 信息
        const res = await http.put('/member/profile', this.profile)
        Toast.success('保存成功')
        window.FlutterNewUser && window.FlutterNewUser.postMessage(JSON.stringify(res.data.result))
      } catch (e) {
        Toast.fail(`保存失败：${JSON.stringify(e?.response?.data)}`)
      }
    }
    // ...mapMutations(['setAvatar'])
  },
  created () {
    emitter.on('fullter_preview_avatar', ({ avatar }) => {
      this.profile.avatar = avatar
    })
    // emitter.on('fullter_submit_profile', (avatar) => {
    //   this.submit()
    // })
    // emitter.on('fullter_inject_profile', (profile) => {
    //   this.profile = profile
    // })
    // emitter.on('fullter_web_toast', (config) => {
    //   Toast(config)
    // })
    http.get('/member/profile').then((res) => {
      this.profile = res.data.result
      this.initAvatar = this.profile.avatar
    })
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    height: 140px;
    width: 100%;
    margin-bottom: 10px;
    padding-top: 20px;
    background: #fff;
    border-radius: 4px;
    a {
      width: 70px;
      height: 70px;
      display: block;
      border-radius: 50%;
      overflow: hidden;
      margin: 0 auto;
      img {
        width: 100%;
        height: 100%;
        vertical-align: middle;
        object-fit: cover;
      }
    }
    p {
      text-align: center;
      color: #999;
      margin-top: 16px;
      font-size: 12px;
    }
  }
}
.van-form {
  border-radius: 4px;
  overflow: hidden;
}
::v-deep .van-field__label {
  flex: none;
  -webkit-box-flex: none;
  -webkit-flex: none;
  flex: none;
  width: 80px;
}
::v-deep .van-radio--horizontal {
  margin-right: 40px;
}
</style>
